package com.ncmmall.mall.controller.business.message;

import com.ncmmall.application.business.message.MessageApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.message.Message;
import com.ncmmall.domain.business.message.QMessage;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统消息
 *
 * @author likaikai
 * @date 2019-07-13 14:18
 */
@Controller
@RequestMapping("/mall/message")
public class MessageController {

    private final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MessageApplication messageApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 消息列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, Message params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());

        Map<String, Object> map = new HashMap<>();
        String hql = buildHql("select m from Message m where type = 1", map, params);

        QueryPage<Message> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Message.class);
        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "mall/message/list";

    }

    /**
     * 条件查询
     *
     * @param hql
     * @param map
     * @param params
     * @return
     */
    private String buildHql(String hql, Map<String, Object> map, Message params) {

        if (StringUtils.isNotBlank(params.getTitle())) {
            hql += " and m.title like :title";
            map.put("title", "%" + params.getTitle() + "%");
        }

        if (params.getStatus() > 0) {
            hql += " and m.status = :status";
            map.put("status", params.getStatus());
        }


        hql += " order by m.createTime desc";

        return hql;
    }


    /**
     * 创建消息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {

        model.addAttribute("_method", "POST");
        model.addAttribute("message", new Message());

        return "mall/message/form";
    }

    /**
     * 创建消息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Message message) {

        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }
            message.setType(1);
            messageApplication.create(message);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加系统消息", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "创建成功");

        } catch (Exception e) {

            logger.error("消息创建异常", e);
            return ImmutableMap.of("status", false, "message", "创建异常");

        }
    }


    /**
     * 编辑消息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    public String modify(Model model, long id) {

        model.addAttribute("_method", "PUT");
        model.addAttribute("message", queryChannelService.findOne(QMessage.message.id.eq(id), Message.class));

        return "mall/message/form";
    }

    /**
     * 编辑消息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Message message) {

        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            messageApplication.modify(message);
            logApplication.eventOfSystem(Securitys.currentUser(), "编辑系统消息", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "编辑成功");

        } catch (Exception e) {

            logger.error("消息编辑异常", e);
            return ImmutableMap.of("status", false, "message", "编辑异常");

        }
    }


    /**
     * 发送消息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> send(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Message params) {

        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }
            Message message = queryChannelService.findOne(QMessage.message.id.eq(params.getId()), Message.class);
            messageApplication.send(message);
            logApplication.eventOfSystem(Securitys.currentUser(), "发送系统消息", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "发送成功");

        } catch (Exception e) {

            logger.error("消息发送异常", e);
            return ImmutableMap.of("status", false, "message", "发送异常");

        }
    }


    /**
     * 删除消息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Message params) {

        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            Message message = queryChannelService.findOne(QMessage.message.id.eq(params.getId()).and(QMessage.message.type.eq(1)), Message.class);

            if (message == null) {
                return ImmutableMap.of("status", false, "message", "消息不存在");
            }

            messageApplication.remove(message);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除系统消息", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "删除成功");

        } catch (Exception e) {

            logger.error("消息删除异常", e);
            return ImmutableMap.of("status", false, "message", "删除异常");

        }
    }


}
